//
//  Api2ASIHttp.m
//  near4u
//
//  Created by apple on 12-5-13.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "Api2ASIHttp.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"

@implementation Api2ASIHttp

@synthesize mIndex;

- (void)dealloc {
    [mIndex release];
    [super dealloc];
}

-(id)  initWithUrl:(NSString*) urlPath 
		  postData:(NSDictionary*)  data
		  delegate:(id)  aDeletgate
		 withIndex:(NSString *) theIndex
onCompletedCallback:(SEL) complectedCallback
{
    self.mIndex = theIndex;
    doneSelector = complectedCallback ;
    mdelegate = aDeletgate;
//    ASIHTTPRequest *requestForm = [ASIHTTPRequest requestWithURL:urlPath];
    ASIFormDataRequest *requestForm = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlPath]];
    requestForm.useCookiePersistence = YES;
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    for ( NSString * key in  [data allKeys]) {
        [requestForm setPostValue:[data objectForKey:key] forKey:key];   
    }
    [requestForm setDelegate:self];
    [requestForm setDidFailSelector:@selector(requestFormFailed:)];
    [requestForm setDidFinishSelector:@selector(requestFormFinished:)];
    [requestForm startAsynchronous];
    
    return self ;
}

- (void)requestFormFinished:(ASIFormDataRequest *)request
{
    // Use when fetching text data
    NSString *responseString = [request responseString];
    NSArray *ret_arr = [NSArray arrayWithObjects:mIndex,responseString,nil];
	[mdelegate performSelector:doneSelector  withObject:ret_arr];
    // Use when fetching binary data
//    NSData *responseData = [request responseData];
}

- (void)requestFormFailed:(ASIFormDataRequest *)request
{
    NSError *error = [request error];
    NSArray *ret_arr = [NSArray arrayWithObjects:mIndex,error,nil];
	[mdelegate performSelector:doneSelector  withObject:ret_arr];
}


@end
